﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Collections.Generic;
using System.Net;
using System.Xml;

using ISS.CaseStudy.BLL;
using ISS.CaseStudy.Entities;



namespace CaseStudy.Web
{
    public partial class Search : System.Web.UI.Page
    {
        private string appId = System.Configuration.ConfigurationManager.AppSettings["BingAppId"].ToString();
        private string siteUrl = System.Configuration.ConfigurationManager.AppSettings["SiteUrl"].ToString();
        private string bingRequestUrl = System.Configuration.ConfigurationManager.AppSettings["BingRequestUrl"].ToString();
        private int pageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageSize"].ToString());
        private string imageFolder = System.Configuration.ConfigurationManager.AppSettings["ImageFolderName"].ToString();
        private string cnSiteRoot = System.Configuration.ConfigurationManager.AppSettings["CNSiteRoot"].ToString();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDropDownLists();
            }
        }

        protected void imgBtnSearch_Click(object sender, EventArgs e)
        {
            lblCurrentPage.Text = "1";
            lblKey.Text = txtSearchKey.Text.Trim();

            if (string.IsNullOrEmpty(lblKey.Text))
            {
                GetDataWithNoKey();
                return;
            }


            HttpWebRequest request = BuildRequest();

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                DisplayResponse(response);
            }
            catch
            {
            }
        }

        protected void btnPre_Click(object sender, EventArgs e)
        {
            int preIndex = int.Parse(lblCurrentPage.Text);
            int currentIndex = preIndex - 1;
            lblCurrentPage.Text = currentIndex.ToString();

            if (string.IsNullOrEmpty(lblKey.Text))
            {
                GetDataWithNoKey();
                return;
            }

            HttpWebRequest request = BuildRequest();

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                DisplayResponse(response);
            }
            catch
            {
            }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            int preIndex = int.Parse(lblCurrentPage.Text);
            int currentIndex = preIndex + 1;
            lblCurrentPage.Text = currentIndex.ToString();

            if (string.IsNullOrEmpty(lblKey.Text))
            {
                GetDataWithNoKey();
                return;
            }

            HttpWebRequest request = BuildRequest();

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                DisplayResponse(response);
            }
            catch
            {
            }
        }

        private HttpWebRequest BuildRequest()
        {
            string[] keys = lblKey.Text.Split(new char[] { ' ' });
            int count = keys.Length;
            string keyword = HttpUtility.UrlEncode(keys[0]);
            for (int i = 1; i < count; i++)
            {
                keyword += "+" + HttpUtility.UrlEncode(keys[i]);
            }

            string requestString = bingRequestUrl
                + "?"
                // Common request fields (required)
                + "AppId=" + appId
                + "&Query=site:" + siteUrl + "+" + keyword
                + "&Sources=Web"

                // Common request fields (optional)
                + "&Version=2.0"
                + "&Market=en-us"
                + "&Adult=Moderate"
                + "&Options=EnableHighlighting"

                // Web-specific request fields (optional)
                + "&Web.Count=20"
                + "&Web.Offset=0"
                + "&Web.Options=DisableHostCollapsing+DisableQueryAlterations";

            // Create and initialize the request.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
                requestString);

            return request;
        }

        private void DisplayResponse(HttpWebResponse response)
        {
            // Load the response into an XmlDocument.
            XmlDocument document = new XmlDocument();
            document.Load(response.GetResponseStream());

            // Add the default namespace to the namespace manager.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(
                document.NameTable);
            nsmgr.AddNamespace(
                "api",
                "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element");

            XmlNodeList errors = document.DocumentElement.SelectNodes(
                "./api:Errors/api:Error",
                nsmgr);

            if (errors.Count > 0)
            {
                // There are errors in the response. Display error details.
                DisplayErrors(errors);
            }
            else
            {
                // There were no errors in the response. Display the
                // Web results.
                DisplayResults(document.DocumentElement, nsmgr);
            }
        }

        private void DisplayResults(XmlNode root, XmlNamespaceManager nsmgr)
        {
            // Add the Web SourceType namespace to the namespace manager.
            nsmgr.AddNamespace(
                "web",
                "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web");

            XmlNode web = root.SelectSingleNode("./web:Web", nsmgr);
            XmlNodeList results = web.SelectNodes(
                "./web:Results/web:WebResult",
                nsmgr);

            string version = root.SelectSingleNode("./@Version", nsmgr).InnerText;
            string searchTerms = root.SelectSingleNode(
                "./api:Query/api:SearchTerms",
                nsmgr).InnerText;
            int offset;
            int.TryParse(
                web.SelectSingleNode("./web:Offset", nsmgr).InnerText,
                out offset);
            int total;
            int.TryParse(
                web.SelectSingleNode("./web:Total", nsmgr).InnerText,
                out total);

            DataSet dataSet = CaseStudyBLL.GetAll();
            if (dataSet.Tables.Count == 0) return;
            DataTable table = dataSet.Tables[0];
            List<SearchResultData> resultDataList = new List<SearchResultData>();

            foreach (XmlNode result in results)
            {
                //string description = result.SelectSingleNode("./web:Description", nsmgr).InnerText;
                //description = description.Replace('\uE000', char.MinValue).Replace('\uE001', char.MinValue);

                string url = result.SelectSingleNode("./web:Url", nsmgr).InnerText;
                url = url.Replace('\uE000', char.MinValue).Replace('\uE001', char.MinValue);
                int startIndex = url.LastIndexOf("/") + 1;
                string title = url.Substring(startIndex);

                foreach (DataRow row in table.Rows)
                {
                    if (ddIndustry.SelectedIndex != 0)
                    {
                        string tempId = row["Industry"].ToString();
                        if (string.IsNullOrEmpty(tempId)) continue;

                        IndustryInfo info = IndustryBLL.GetInfo(tempId);
                        if (info == null) continue;

                        if (!HttpUtility.HtmlDecode(info.Value).Equals(ddIndustry.SelectedValue))
                            continue;
                    }

                    if (ddClient.SelectedIndex != 0)
                    {
                        string tempId = row["Client"].ToString();
                        if (string.IsNullOrEmpty(tempId)) continue;

                        ClientInfo info = ClientBLL.GetInfo(tempId);
                        if (info == null) continue;

                        if (!HttpUtility.HtmlDecode(info.Value).Equals(ddClient.SelectedValue))
                            continue;

                    }

                    if (ddService.SelectedIndex != 0)
                    {
                        string tempId = row["Service"].ToString();
                        if (string.IsNullOrEmpty(tempId)) continue;

                        ServiceInfo info = ServiceBLL.GetInfo(tempId);
                        if (info == null) continue;

                        if (!HttpUtility.HtmlDecode(info.Value).Equals(ddService.SelectedValue))
                            continue;
                    }

                    if (row["FileName"].ToString().Equals(title))
                    {
                        SearchResultData resultData = new SearchResultData();
                        resultData.Id = row["Id"].ToString();
                        resultData.Title = row["Title"].ToString();
                        if (!string.IsNullOrEmpty(row["Image"].ToString()))
                        {
                            resultData.ImageUrl = cnSiteRoot + "/" + imageFolder + "/" + row["Image"].ToString();
                        }
                        else
                        {
                            resultData.ImageUrl = "images/default.png";
                        }
                        resultData.Description = row["Description"].ToString();
                        resultData.Url = "CaseStudyView.aspx?id=" + resultData.Id;

                        resultDataList.Add(resultData);
                        break;
                    }
                }
            }

            BindData(resultDataList);

        }

        private void DisplayErrors(XmlNodeList errors)
        {
            Response.Write(string.Format("<div>Errors:</div>"));
            Response.Write(string.Format("<div>&nbsp;</div>"));
            foreach (XmlNode error in errors)
            {
                foreach (XmlNode detail in error.ChildNodes)
                {
                    Response.Write(string.Format("<div>{0}:{1}</div>", detail.Name, detail.InnerText));

                }


            }
        }

        private void BindDropDownLists()
        {
            ddIndustry.Items.Add("All");
            ddClient.Items.Add("All");
            ddService.Items.Add("All");

            DataSet dataSetTechnology = TechnologyBLL.GetAll();
            DataSet dataSetIndustry = IndustryBLL.GetAll();
            foreach (DataRow row in dataSetIndustry.Tables[0].Rows)
            {
                ddIndustry.Items.Add(HttpUtility.HtmlDecode(row["Value"].ToString()));
            }

            DataSet dataSetClient = ClientBLL.GetAll();
            foreach (DataRow row in dataSetClient.Tables[0].Rows)
            {
                ddClient.Items.Add(HttpUtility.HtmlDecode(row["Value"].ToString()));
            }

            DataSet dataSetService = ServiceBLL.GetAll();
            foreach (DataRow row in dataSetService.Tables[0].Rows)
            {
                ddService.Items.Add(HttpUtility.HtmlDecode(row["Value"].ToString()));
            }
        }

        private void BindData(List<SearchResultData> resultDataList)
        {
            resultFoot.Visible = true;

            PagedDataSource pds = new PagedDataSource();
            pds.DataSource = resultDataList;
            pds.AllowPaging = true;
            pds.PageSize = pageSize;
            pds.CurrentPageIndex = int.Parse(lblCurrentPage.Text) - 1;

            int startCount = pageSize * pds.CurrentPageIndex + 1;
            int endCount = startCount + pageSize - 1;
            if (endCount > resultDataList.Count)
                endCount = resultDataList.Count;

            lblLeftRemind.Text = "搜索结果 (" + resultDataList.Count.ToString() + ")";
            if (endCount == 0)
                lblRightRemind.Text = "显示从 0 到 0";
            else
                lblRightRemind.Text = "显示从 " + startCount.ToString() + " 到 " + endCount.ToString();

            if (pds.CurrentPageIndex == 0)
            {
                btnPre.Enabled = false;
            }
            else
            {
                btnPre.Enabled = true;
            }

            if (pds.CurrentPageIndex == pds.PageCount - 1)
            {
                btnNext.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
            }

            rptResults.DataSource = pds;
            rptResults.DataBind();

            if (rptResults.Items.Count == 0)
            {
                resultFoot.Visible = false;
            }
        }

        private void GetDataWithNoKey()
        {
            DataSet dataSet = CaseStudyBLL.GetAll();
            if (dataSet.Tables.Count == 0) return;
            DataTable table = dataSet.Tables[0];
            List<SearchResultData> resultDataList = new List<SearchResultData>();

            foreach (DataRow row in table.Rows)
            {
                if (ddIndustry.SelectedIndex != 0)
                {
                    string tempId = row["Industry"].ToString();
                    if (string.IsNullOrEmpty(tempId)) continue;

                    IndustryInfo info = IndustryBLL.GetInfo(tempId);
                    if (info == null) continue;

                    if (!HttpUtility.HtmlDecode(info.Value).Equals(ddIndustry.SelectedValue))
                        continue;
                }

                if (ddClient.SelectedIndex != 0)
                {
                    string tempId = row["Client"].ToString();
                    if (string.IsNullOrEmpty(tempId)) continue;

                    ClientInfo info = ClientBLL.GetInfo(tempId);
                    if (info == null) continue;

                    if (!HttpUtility.HtmlDecode(info.Value).Equals(ddClient.SelectedValue))
                        continue;
                }

                if (ddService.SelectedIndex != 0)
                {
                    string tempId = row["Service"].ToString();
                    if (string.IsNullOrEmpty(tempId)) continue;

                    ServiceInfo info = ServiceBLL.GetInfo(tempId);
                    if (info == null) continue;

                    if (!HttpUtility.HtmlDecode(info.Value).Equals(ddService.SelectedValue))
                        continue;
                }

                SearchResultData resultData = new SearchResultData();
                resultData.Id = row["Id"].ToString();
                resultData.Title = row["Title"].ToString();
                if (!string.IsNullOrEmpty(row["Image"].ToString()))
                {
                    resultData.ImageUrl = cnSiteRoot + "/" + imageFolder + "/" + row["Image"].ToString();
                }
                else
                {
                    resultData.ImageUrl = "images/default.png";
                }
                resultData.Description = row["Description"].ToString();
                resultData.Url = "CaseStudyView.aspx?id=" + resultData.Id;

                resultDataList.Add(resultData);
            }

            BindData(resultDataList);
        }
    }
}
